package com.heo.music.player.converter;


import com.heo.music.player.dto.output.PageOutput;
import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.domain.Page;

import java.util.List;
import java.util.stream.Collectors;

/**
 * dto转换
 * @author 星天无极
 **/
@RequiredArgsConstructor
public abstract class AbstractConverter<T, R> implements Converter<T, R>, InitializingBean {

    protected final ModelMapper modelMapper;

    @Override
    public List<R> convert(List<T> t) {
        return t.stream().map(this::convert).collect(Collectors.toList());
    }

    @Override
    public PageOutput<R> convert(Page<T> t) {
        PageOutput<R> r = new PageOutput<>();
        r.setTotalPages(t.getTotalPages());
        r.setTotalElements(t.getTotalElements());
        r.setData(convert(t.getContent()));
        return r;
    }

    @Override
    public void afterPropertiesSet() {
        modelMapper.addConverter((org.modelmapper.Converter<T, R>) mappingContext -> {
            T source = mappingContext.getSource();
            return this.convert(source);
        });
    }
}
